from .WechatAuto import (Messages, Files, Contacts, FriendSettings, GroupSettings, AutoReply, Call, Moments,
                         WechatSettings)


class WechatAuto:
    """
    微信自动化主类
    包装所有微信自动化功能
    """

    def __init__(self):
        self.messages = Messages()
        self.files = Files()
        self.contacts = Contacts()
        self.friend_settings = FriendSettings()
        self.group_settings = GroupSettings()
        self.auto_reply = AutoReply()
        self.call = Call()
        self.moments = Moments()
        self.wechat_settings = WechatSettings()

    def send_message_to_friend(self, friend_name: str, message: str, at: list = [], at_all: bool = False, tickle: bool = False, search_pages: int = 5, wechat_path: str = None, is_maximize: bool = True, close_wechat: bool = True) -> bool:

        """
        发送单条消息给好友
        """
        try:
            self.messages.send_message_to_friend(friend=friend_name, message=message, at=[], tickle=False, search_pages=5, wechat_path=None, is_maximize=True, close_wechat=True)
            return True
        except Exception:
            return False

    def send_message_to_group(self, group_name: str, message: str, at: list = [], at_all: bool = False, tickle: bool = False, search_pages: int = 5, wechat_path: str = None, is_maximize: bool = True, close_wechat: bool = True) -> bool: 

        """
        发送单条消息给群组
        """
        print("发送群组消息:", group_name)
        print("neirong ", message)
        try:
            self.messages.send_message_to_friend(friend=group_name, message=message)
            return True
        except Exception:
            return False

    def send_messages_to_friend(self, friend_name: str, messages: list) -> bool:
        """
        发送多条消息给好友
        """
        try:
            self.messages.send_messages_to_friend(friend_name, messages)
            return True
        except Exception:
            return False

    def send_messages_to_group(self, group_name: str, messages: list) -> bool:
        """
        发送多条消息给群组
        """
        try:
            self.messages.send_messages_to_friend(group_name, messages)
            return True
        except Exception:
            return False

    def check_new_message(self, duration: str = "10s", check_interval: bool = False, max_checks: int = None) -> list:
        """
        检查新消息
        
        Args:
            duration (str): 监听消息持续时长，格式:'s','min','h'单位:s/秒,min/分,h/小时
                            如果check_interval为True，则表示每隔duration秒执行一次check方法
                            如果check_interval为False，则表示在duration时间结束后执行一次check方法
            check_interval (bool): 是否启用间隔检查模式，默认为False
            max_checks (int): 最大检查次数，仅在check_interval为True时有效，默认为None（无限循环直到手动中断）
        
        Returns:
            list: 新消息列表
        """
        try:
            from pywechat.WechatAuto import check_new_message
            from pywechat.WechatTools import match_duration
            import time
            
            # 如果启用间隔检查模式
            if check_interval:
                # 将duration转换为秒数
                seconds = match_duration(duration)
                if not seconds:
                    raise ValueError(f"无效的duration格式: {duration}，正确格式如: '30s', '1min', '1h'")
                
                all_results = []
                check_count = 0
                
                try:
                    # 循环检查，直到达到最大检查次数或手动中断
                    while max_checks is None or check_count < max_checks:
                        # 执行一次检查，直接调用WechatAuto中的check_new_message方法
                        # 注意：这里不能调用self.check_new_message()，否则会导致递归
                        result = check_new_message(duration=None)  # 传入None表示只检查一次
                        
                        # 增加检查计数
                        check_count += 1
                        
                        # 如果找到新消息，添加到结果列表但不返回，继续监听
                        if result:
                            new_messages = result if isinstance(result, list) else [result]
                            all_results.extend(new_messages)
                            print(f"收到{len(new_messages)}条新消息，继续监听中...")
                            # 打印新消息的详细内容
                            for i, msg in enumerate(new_messages):
                                print(f"新消息 {i+1}:")
                                for key, value in msg.items():
                                    print(f"  {key}: {value}")
                        
                        # 如果达到最大检查次数，则退出循环
                        if max_checks is not None and check_count >= max_checks:
                            print(f"已达到最大检查次数{max_checks}，退出监听")
                            break
                            
                        # 等待指定的时间间隔后再次检查
                        if not result:
                            print(f"未找到新消息，{seconds}秒后再次检查...")
                        time.sleep(seconds)
                        
                except KeyboardInterrupt:
                    print("检查新消息已手动中断")
                
                return all_results
            else:
                # 原有的单次检查逻辑
                result = check_new_message(duration=duration)
                return result if result else []
        except Exception as e:
            print(f"检查新消息失败: {e}")
            return []
